<template>
  <div class="dialog">
    <div v-if="viewDetail">
      <pre style="display: block; font-size: 14px">{{ viewNote }}</pre>
      <el-button type="danger" @click="viewDetail=false">返 回</el-button>
    </div>
    <div v-else>
      <el-tabs v-model="activeName" @tab-click="handleClickTab">
        <el-tab-pane label="素材列表" name="first">
          <el-container>
            <el-header style="height: 35px">
              <div v-loading="listLoading" class="top">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div style="flex: 1;">
                    <el-input v-model="kwInput" placeholder="请输入内容" size="mini">
                      <el-select slot="prepend" v-model="m_type" placeholder="选择类型" @change="handleSearch">
                        <el-option label="所有类型" value="all" />
                        <el-option label="附件" value="attachment" />
                        <el-option label="PAA(also ask)" value="google_ask" />
                        <el-option label="框架" value="google_serp" />
                        <el-option label="段落" value="paragraph" />
                        <el-option label="top link" value="google_links" />
                        <el-option label="video" value="video" />
                        <el-option label="手动添加" value="manual" />
                      </el-select>
                      <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
                    </el-input>
                  </div>
                  <el-button type="primary" style="margin-left: 10px;" @click="handleCreate">添加</el-button>
                </div>
              </div>
            </el-header>
            <el-main style="margin-top: 1px;padding-top:1px">
              <div style="height: 600px">
                <el-card v-for="(item, index) in data" :key="index" class="box-card" :body-style="{ padding: '10px' }" style="display: block">
                  <div slot="header" class="clearfix">
                    <span style="font-size: xx-small">{{ item.title || item.type }}</span>
                    <el-select v-model="item.post_to" style="float: right" placeholder="推广到" filterable clearable size="mini">
                      <el-option v-for="(node, index) in post_to_websites" :key="index" :label="node.label" :value="node.value" />
                    </el-select>
                    <el-button style="float: right;color: red" size="mini" type="text" @click="handleAction('delete', item)">删除</el-button>
                    <el-button style="float: right;margin-right: 10px" size="mini" type="text" @click="handleAction('edit', item)">提交修改</el-button>
                  </div>
                  <div class="text item" style="font-size: smaller">
                    <div v-if="item.type === 'google_links' || item.type === 'video'">
                      <ul>
                        <li v-for="gg in item.note.split('\n')" :key="gg"><el-link v-if="gg.indexOf('http') > -1" :href="gg" target="_blank">{{ get_domain_from_url(gg) }}</el-link></li>
                      </ul>
                    </div>
                    <div v-else-if="item.type === 'attachment'">
                      <el-image v-if="item.note.indexOf('image') !== -1" :src="item.link" />
                      <!-- Support for MP4 video format -->
                      <video v-else-if="item.note.indexOf('mp4') !== -1" :src="item.link" controls />
                      <audio v-else-if="item.note.indexOf('mp3') !== -1 || item.note.indexOf('wav') !== -1 || item.note.indexOf('ogg') !== -1" controls :src="item.link" />
                      <el-link v-else :href="item.link" target="_blank">{{ item.title }}</el-link>
                    </div>
                    <el-input v-else v-model="item.note" type="textarea" :rows="15" />
                    <a v-if="item.link && item.link.indexOf('http')>-1" style="display: block" target="_blank" :href="item.link">from:{{ get_domain_from_url(item.link) }}</a>
                  </div>
                </el-card>
              </div>

            </el-main>
            <el-footer>
              <el-pagination
                v-if="data.length"
                background
                class="mt-pagination"
                :current-page="page"
                :page-sizes="[10,20,50,100, 1000]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
              />
            </el-footer>
          </el-container>

        </el-tab-pane>

        <el-tab-pane label="内链列表" name="innerlink">
          <cms-inner-link :domain="root_domain" />
        </el-tab-pane>
        <el-tab-pane label="附件列表" name="third">
          <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
        </el-tab-pane>
        <el-tab-pane label="AIShortCode" name="forth">
          <span>常用AI Prompts</span>
          <el-row v-for="(item, index) in promptShortCodes" :key="`prompt-${index}-${item.shortcode}`" style="margin: 5px; align-items: center;">
            <el-col :span="18">
              <el-input v-model="item.shortcode" size="mini" placeholder="请输入内容" />
            </el-col>
            <el-col :span="6">
              <el-button size="mini" type="primary" @click="copyShortCode(item)">复制</el-button>
            </el-col>
          </el-row>
          <el-divider>当前话题shortcode</el-divider>
          <el-row v-for="(item, index) in topicShortCodes" :key="`topic-${index}-${item.shortcode}`" style="margin: 5px; align-items: center;">
            <el-col :span="18">
              <el-input v-model="item.shortcode" size="mini" placeholder="请输入内容" :title="item.name" />
            </el-col>
            <el-col :span="6">
              <el-button size="mini" type="primary" :title="item.name" @click="copyShortCode(item)">复制</el-button>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 添加素材的弹窗 -->
    <el-dialog title="添加素材" :visible.sync="addDialogVisible" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="80px">
        <el-form-item label="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="temp.note" type="textarea" rows="20" />
        </el-form-item>
        <el-form-item label="推广到">
          <el-select v-model="temp.post_to" placeholder="推广平台" filterable clearable>
            <el-option v-for="(item, index) in post_to_websites" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="createloading" @click="confirmAdd">确 认</el-button>
      </span>
    </el-dialog>
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/topicmaterial'
import { GetPromptShortCode } from '@/api/cms/aiprompt'
// import { Get as GetTopic } from '@/api/cms/topic'
import qs from 'qs'
import Crmfilesmanager from '../../../components/crmfilesmanager'
import CmsInnerLink from './cmsinnerlink'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Topicmaterial',
  components: { CmsInnerLink, Crmfilesmanager },
  props: ['webVisible', 'topic_id', 'topic_title', 'root_domain'],
  data() {
    return {
      domain: '',
      post_to_websites: [
        {
          label: '不推广',
          value: ''
        },
        {
          label: 'medium.com(自动)',
          value: 'medium.com'
        },
        {
          label: 'quora.com(自动)',
          value: 'quora.com'
        },
        {
          label: '保存为新框架',
          value: 'save_as_topic'
        }
      ],
      createloading: false,
      viewDetail: false,
      promptShortCodes: [],
      viewTitle: '',
      viewNote: '',
      activeName: 'first',
      m_type: 'all',
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: 'create_at',
      order_desc: '1',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      action: 'create',
      dialogVisible: false,
      addDialogVisible: false,
      topicShortCodes: [],
      title: '',
      temp: {
        title: '',
        note: '',
        post_to: '',
        topic_id: this.topic_id
      },
      width: '',
      projects: [],
      innerDialogVisible: false
    }
  },
  watch: {
    webVisible(v) {
      this.dialogVisible = v
    },
    topic_id(v) {
      if (v) {
        this.getList()
      }
    }
  },
  created() {
    this.getList()
    this.hanldeGetShortCodes()
  },
  methods: {
    copyShortCode(item) {
      navigator.clipboard.writeText(item.shortcode).then(() => {
        this.$message.success('ShortCode 已复制到剪贴板')
      }).catch(error => {
        console.error('复制失败:', error)
        this.$message.error('复制失败')
      })
    },
    handleInsertFile(item) {
      // item 转化为json字符串
      Post({
        title: item.filename,
        type: 'attachment',
        link: item.url,
        note: JSON.stringify(item, null, 2),
        topic_id: this.topic_id
      }).then(response => {
        this.getList()
        this.$message.success('添加成功')
      })
    },
    get_domain_from_url(url) {
      if (url.indexOf('://') > -1) {
        return url.split('://')[1].split('/')[0]
      }
      return url.substring(0, 10)
    },
    resetTemp() {
      this.temp = {
        title: '',
        note: '',
        post_to: '',
        topic_id: this.topic_id
      }
      console.log('create')
    },
    handleViewDetail(row) {
      this.viewTitle = row.title
      this.viewNote = row.note
      this.viewDetail = true
    },
    handleClickTab(tab, event) {
      // 已删除添加标签页的相关逻辑
    },
    hanldeGetShortCodes() {
      GetPromptShortCode().then(response => {
        this.promptShortCodes = response.data.data
      })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        type: this.m_type,
        topic_id: this.topic_id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
          this.topicShortCodes = []
          this.topicShortCodes.push({
            name: '取当前话题框架标题',
            'shortcode': '{{topic_' + this.topic_id + '_title}}'
          })
          this.topicShortCodes.push({
            name: '取当前话题框架关键词',
            'shortcode': '{{topic_' + this.topic_id + '_keyword}}'
          })
          this.topicShortCodes.push({
            name: '取当前话题框架内容',
            'shortcode': '{{topic_' + this.topic_id + '_description}}'
          })
          this.topicShortCodes.push({
            'name': '子框架标题随机取一个',
            'shortcode': '{{topic_' + this.topic_id + '_title_random_1}}'
          })
          this.topicShortCodes.push({
            'name': '子框架关键词随机取一个',
            'shortcode': '{{topic_' + this.topic_id + '_keyword_random_1}}'
          })
          this.topicShortCodes.push({
            'name': '子框架内容随机取一个',
            'shortcode': '{{topic_' + this.topic_id + '_description_random_1}}'
          })
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.handleCreate() // 改为调用handleCreate方法
          break
        case 'delete':
          this.width = '30%'
          this.temp = Object.assign({}, row)
          this.confirm()
          break
        case 'edit':
          Put(row.id, row).then((response) => {
            this.$message.success('修改成功')
            row.editable = false
          })
          break
      }
    },
    confirm() {
      this.temp.topic_id = this.topic_id
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (_data.topic_id === '') {
            alert('必须选择框架')
            return
          }
          this.createloading = true
          Post({
            title: _data.title,
            note: _data.note,
            topic_id: _data.topic_id

          }
          ).then(response => {
            this.innerDialogVisible = false
            this.activeName = 'first'
            this.getList()
            this.$message.success('保存成功')
            this.createloading = false
          }).catch(e => {
            this.createloading = false
            this.$message.error('保存失败')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.activeName = 'first'
            this.getList()
            this.$message.success('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, {
            title: _data.title,
            note: _data.note,
            topic_id: _data.topic_id
          }).then((response) => {
            this.innerDialogVisible = false
            this.activeName = 'second'
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMetrialDialog', false)
    },
    handleCreate() {
      this.resetTemp()
      this.action = 'create'
      this.addDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },

    confirmAdd() {
      this.temp.topic_id = this.topic_id
      const _data = this.temp

      if (_data.topic_id === '') {
        this.$message.error('必须选择框架')
        return
      }

      this.createloading = true
      Post({
        title: _data.title,
        note: _data.note,
        topic_id: _data.topic_id,
        post_to: _data.post_to
      }).then(response => {
        this.addDialogVisible = false
        this.getList()
        this.$message.success('保存成功')
        this.createloading = false
      }).catch(e => {
        this.createloading = false
        this.$message.error('保存失败')
      })
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 150px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 0px;
    margin-bottom: 5px;
    margin-top: 2px;
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }
  .dialog >>> .el-card__header {
    padding: 10px 10px;
    border-bottom: 0px;
  }
  .dialog >>> .el-card__body {
    padding: 10px 10px;
  }
  .dialog >>> .el-card {
   margin-bottom: 10px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
    padding-top: 5px;
  }

  .mt-dialog >>> .el-dialog__header {
    padding-bottom: 5px;
    padding-top: 10px;
  }
</style>
